<?php

namespace app\api\controller;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;

use think\Config;
use think\Validate;//验证
use fast\Random;
use fast\Http;

use app\api\controller\Xiaohe;
use app\api\controller\Yuyue;



use Endroid\QrCode\QrCode as QrCode2;
use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\Label\Label;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;


/**
 * 二维码⚽︎
 */
class Qrcode extends Xiaohe
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 用户获取我的分享二维码
     *
     * @return void
     */
    public function user_get_my_qr($self=false)
    {

        $data['id'] = $this->auth->id;
        $data['type'] = 1;

        //判断文件存在不
        $path = $this->get_img_path($data['type'],$data['id']);
        if(is_file($path)){
            $json['my_qr'] = $this->request->domain().'/'.$path;            
        }else{
            //生成分享二维码            
            $json['my_qr'] = $this->request->domain().'/'.$this->create_wx_qr($data);            
        }
        if($self){
            return $json['my_qr'];
        }
        return json($json);
    }


    /**
     * 获取场地二维码(弃用)
     * @ApiInternal()
     * @param int $ltd_id
     * @return void
     */
    public function get_ltd_qr($admin_id,$self=false)
    {
        $data['id'] = $admin_id;
        $data['type'] = 3;//场地
        //判断文件存在不
        $path = $this->get_img_path($data['type'],$data['id']);
        if(is_file($path)){
            $json['my_qr'] = '/'.$path;   //  $this->request->domain().
        
        }else{
            //生成分享二维码            
            $json['my_qr'] = '/'.$this->create_wx_qr($data);    //  $this->request->domain().        
        }


        //2020-12-25 16:50:42
        // 上传二维码
        if($self){
            return $json['my_qr'];
        }
        return json($json['my_qr']);
    }





    

    /**
     * 创建二维码  返回文件地址
     * @ApiInternal()
     *
     * @param [type] $data
     * @return void
     */
    public function create_wx_qr($data)
    {

        //获取路径
        
        $id = $data['id'];
        $file_path = $this->get_img_path($data['type']);
        
        // halt($data['type']);
        // halt($data);
        // halt($file_path);
        switch ($data['type']) {
            case '1':
                
                //用户
                $path="pages/index/index?pid=".$id;
                // $file_path = $this->get_img_path();
                break;
            // case '2':
            //     //手艺人
            //     $path="pages/againCode/againCode?id=".$id.'&sid='.$data['storesid'].'&stime='.$data['sb_time'].'&etime='.$data['xb_time'];
            //     // $file_path = $this->get_img_path().'worker/';
            //     break;
            case '3':
                //场地
                $path="pages/s_storesxq/s_storesxq?id=".$id;
                // $file_path = $this->get_img_path().'ltd/';
                break;
            default:
                # code...
                break;
        }


        $app = $this->get_app();
        $response = $app->app_code->get($path, [
            'width' => 98,
            'line_color' => [
                'r' => 0,
                'g' => 0,
                'b' => 0,
            ],
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save($file_path,$id.'.png');
            // halt($filename);
            return $file_path.$filename;
        }
    }




    
    /**
     * 传入uid 返回文件地址  或者不要后缀的地址
     * @ApiInternal()
     *
     * @param [type] $data
     * @return void
     */
    public function get_img_path($type = 1,$id=null)
    {   
        switch ($type) {
            case '1':
                $file_path = 'assets/qr/user/';
                break;
            // case '2':
            //     //手艺人
            //     $file_path = 'assets/qr/worker/';
            //     break;
            case '3':
                //店铺
                $file_path = 'assets/qr/space/';
                break;
            default:
                $file_path = 'assets/qr/';
                break;
        }

        if($id){
            return $file_path.$id.'.png';
        }else{
            return $file_path;
        }
    }

    /**
     * 获取开门二维码
     *
     * @param int $uid 用户id
     * @param boolean $self 自
     * @return void
     */
    public function get_in_door_qrcode($uid,$self=false)
    {


        $data['uid'] = $this->auth->id;
        $data['status'] = 'in';
        $data['time'] = time();
        $data['type'] = '1';//1个人到场 2包场
        $endata = json_encode($data);

        $dest = 'assets/qr/in_door/';
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }

        $str = $this->enStr($endata);
        $json['qr'] = '/'.$this->create_qr($str,'assets/qr/in_door/'.$this->auth->id.'.png');

        if($self){
            return $json['qr'];
        }else{
            return json($json);
        }
    }

    /**
     * 获取个人出门二维码（到场
     *
     * @param string $order 订单
     * @param boolean $self 自
     * @return void
     */
    public function get_out_door_qrcode($order,$self=false)
    {
        //查询订单是否已支付
        $order_data = Db::name('order')->where('order',$order)->find();
        if($order_data['pay_status']=='2'){

            $data['ps'] = '到场出门';
            $data['uid'] = $order_data['uid'];
            $data['status'] = 'out';
            $data['time'] = time();
            $data['order'] = $order;
            $data['type'] = '1';//1个人到场 2包场
            $endata = json_encode($data);
    
            $dest = 'assets/qr/out_door/';
            if (!is_dir($dest)) {
                mkdir($dest, 0755, true);
            }
    
            $str = $this->enStr($endata);
            $json['qr'] = '/'.$this->create_qr($str,'assets/qr/out_door/'.$order.'.png');
    
            if($self){
                return $json['qr'];
            }else{
                return json($json);
            }
        }
    }

    /**
     * 获取包场出门二维码
     *
     * @param string $order 订单号
     * @param boolean $self false
     * @return void
     */
    public function get_baochang_out_door_qrcode($order,$self=false)
    {
            //查询订单是否已支付
            $order_data = Db::name('order')->where('order',$order)->find();
            // if($order_data['uid']!=$this->auth->id){
            //     $this->error('非自己的订单');
            // }
            if($order_data['pay_status']=='2'){
    
    
                $data['uid'] = $order_data['uid'];
                $data['status'] = 'out';
                $data['order'] = $order;
                $data['time'] = time();
                $data['type'] = '2';//1个人到场 2包场
                $endata = json_encode($data);
        
                $dest = 'assets/qr/out_door/';
                if (!is_dir($dest)) {
                    mkdir($dest, 0755, true);
                }
        
                $str = $this->enStr($endata);
                $json['qr'] = '/'.$this->create_qr($str,'assets/qr/out_door/'.$order.'.png');
        
                if($self){
                    return $json['qr'];
                }else{
                    return json($json);
                }
            }
    }



    /**
     * 获取包场进门二维码
     *
     * @param string $order 订单号
     * @param boolean $self false
     * @return void
     */
    public function get_baochang_in_door_qrcode($order,$self=false)
    {
            //查询订单是否已支付
            $order_data = Db::name('order')->where('order',$order)->find();
            if($order_data['uid']!=$this->auth->id){
                $this->error('非自己的订单');
            }
            if($order_data['pay_status']=='2'){
    
    
                $data['uid'] = $order_data['uid'];
                $data['status'] = 'in';
                $data['order'] = $order;
                $data['time'] = time();
                $data['type'] = '2';//1个人到场 2包场
                $endata = json_encode($data);
        
                $dest = 'assets/qr/in_door/';
                if (!is_dir($dest)) {
                    mkdir($dest, 0755, true);
                }
        
                $str = $this->enStr($endata);
                $json['qr'] = '/'.$this->create_qr($str,'assets/qr/in_door/'.$order.'.png');
        
                if($self){
                    return $json['qr'];
                }else{
                    return json($json);
                }
            }
    }

    /**
     * 获取分享包场二维码
     * @ApiInternal()
     * @param string $order 订单
     * @return void
     */
    public function get_share_baochang_qrcode($order)
    {
        //查询订单是否已支付
        $order_data = Db::name('order')->where('order',$order)->find();
        if($order_data['uid']!=$this->auth->id){
            $this->error('非自己的订单');
        }
        if($order_data['pay_status']=='2'){
            $data['uid'] = $order_data['uid'];
            $data['order'] = $order;
            $data['time'] = time();
            $data['type'] = '2';//1个人到场 2包场
            


            $path="pages/i_xqbm/i_xqbm?".http_build_query($data);
            
            $file_path = 'assets/qr/share_baochang/';
                if (!is_dir($file_path)) {
                    mkdir($file_path, 0755, true);
                }
            $app = $this->get_app();
            $response = $app->app_code->get($path, [
                'width' => 98,
                'line_color' => [
                    'r' => 0,
                    'g' => 0,
                    'b' => 0,
                ],
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $response->save($file_path,$order.'.png');
                // halt($filename);
                return $file_path.$filename;
            }



            // $endata = json_encode($data);
        }
    }

    /**
     * 创建二维码  返回文件地址
     * @ApiInternal()
     * @param string $uid
     * @param string $file_path
     * @return void
     */
    protected function create_qr($str,$file_path)
    {
        
     


        $qrCode = new QrCode2();
        $qrCode->setText($str); //设置二维码上的内容

        $qrCode->setSize(300);  //二维码尺寸

        $qrCode->setWriterByName('png'); //设置输出的二维码图片格式

        $qrCode->setMargin(10);

        $qrCode->setEncoding('UTF-8');

        // $qrCode->setErrorCorrectionLevel(ErrorCorrectionLevel::HIGH()); //设置二维码的纠错率，可以有low、medium、quartile、hign多个纠错率

        $qrCode->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0]); //设置二维码的rgb颜色和透明度a，这里是黑色

        $qrCode->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]); //设置二维码图片的背景底色，这里是白色

        //可能的指定二维码下方的文字，写死15px的字体大小，字体

        // $qrCode->setLabelFontPath(__DIR__.'/vendor/endroid/qr-code/assets/fonts/noto_sans.otf'); //字体路径

        // $qrCode->setLabel('二维码下方的文字1'); //文字

        $qrCode->setLabelFontSize(16); //字体大小

        //或统一用setLabel('二维码下方的文字','字体大小','字体路径','对齐方式')来设置

        // $qrCode->setLabel('二维码下方的文字2', 16, __DIR__.'/vendor/endroid/qr-code/assets/fonts/noto_sans.otf', LabelAlignment::CENTER());

        $qrCode->setLabelMargin(['t'=>50]); //设置标签边距 array('t' => 10,'r' => 20,'b' => 10,'l' => 30)

        //如果要加上logo水印，则在调用setLogoPath和setLogoSize方法

        // $qrCode->setLogoPath(__DIR__.'/logo.png'); //logo水印图片的所在的路径

        $qrCode->setLogoSize(150, 200); //设置logo水印的大小，单位px ，参数如果是一个int数字等比例缩放


        //保存二维码
        if(is_file($file_path)){
            unlink($file_path);
        }
        $qrCode->writeFile($file_path);
     

        

        // $app = $this->get_app();
        // $response = $app->app_code->get($path, [
        //     'width' => 98,
        //     'line_color' => [
        //         'r' => 0,
        //         'g' => 0,
        //         'b' => 0,
        //     ],
        // ]);
        // if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
        //     $filename = $response->save($file_path,$uid.'.png');
        //     // halt($filename);
        return $file_path;
        // }

    }
 

}